package com.lufan.config;

import com.google.gson.Gson;
import com.lufan.data.dto.DownloadInfo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.StandardCharsets;

@Configuration
public class RedisConfig {
    public static class GsonRedisSerializer<T> implements RedisSerializer<T> {
        private final Gson gson;
        private final Class<T> clazz;

        public GsonRedisSerializer(Class<T> clazz) {
            this.clazz = clazz;
            this.gson = new Gson();
        }

        @Override
        public byte[] serialize(T t) throws SerializationException {
            if (t == null) {
                return new byte[0];
            }
            try {
                return gson.toJson(t).getBytes(StandardCharsets.UTF_8);
            } catch (Exception ex) {
                throw new SerializationException("Could not serialize object: " + ex.getMessage(), ex);
            }
        }

        @Override
        public T deserialize(byte[] bytes) throws SerializationException {
            if (bytes == null || bytes.length == 0) {
                return null;
            }
            try {
                String json = new String(bytes, StandardCharsets.UTF_8);
                return gson.fromJson(json, clazz);
            } catch (Exception ex) {
                throw new SerializationException("Could not deserialize object: " + ex.getMessage(), ex);
            }
        }
    }


    @Bean
    public RedisTemplate<String, DownloadInfo> downloadInfoRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, DownloadInfo> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GsonRedisSerializer<>(DownloadInfo.class));
        template.setHashValueSerializer(new GsonRedisSerializer<>(DownloadInfo.class));
        template.afterPropertiesSet();
        return template;
    }
}